#include <jni.h>
#include <stdio.h>
#include "ObjectArrayTest.h"
#define NELEM(x) (sizeof(x)/sizeof(x[0]))

JNIEXPORT jobjectArray JNICALL Java_ObjectArrayTest_initInt2DArray(JNIEnv *env, jclass cls, int size)
{
	jobjectArray result;
	int i;
	// obtain a reference of the element class of the two-dimensional int array
	jclass intArrCls  = (*env)->FindClass(env, "[I");
	if (intArrCls == NULL) {
		return NULL;
	}
	//allocates an array whose element type is denoted by the intArrCls class reference. 
	//The NewObjectArray function only allocates the first dimension
	result = (*env)->NewObjectArray(env, size, intArrCls, NULL);
	if (result == NULL) {
		return NULL;
	}

	for (i=0; i<size; i++) {
		jint tmp[256]; //make sure it is large enough
		jint j;
		jintArray iarr = (*env)->NewIntArray(env, size);
		if (iarr == NULL) {
			return NULL;
		}
		for (j=0; j<size; j++) {
			tmp[j] = i + j;
		}
		// copies the contents of the tmp[] buffer into the newly allocated one-dimensional arrays
		(*env)->SetIntArrayRegion(env, iarr, 0, size, tmp);
		(*env)->SetObjectArrayElement(env, result, i, iarr);
		//ensures that the virtual machine does not run out of the memory used 
		//to hold JNI references such as iarr
		(*env)->DeleteLocalRef(env, iarr);
	}
	return result;
}


/**
 * @brief 在加载动态链接库的时候，JVM会去尝试查找此函数，可以在此函数做一些 native函数的注册
 *
 * @retval JNI的版本
 */
/*
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved){
    printf("I'm in JNI_OnLoad \n");
    //每个java进程只有一个JavaVM
    JNIEnv *env = NULL;
    jint result = -1;
    if (vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) {
        return result;
    }
    
    static JNINativeMethod gMethods[] = {
        {
            "get",
            "()Ljava/lang/jint",
            (void*)Java_HelloWorld_get,            
        },
        {
            "set",
            "(Ljava/lang/jint)V",
            (void*)Java_HelloWorld_set,
        }
    };
	jclass clazz = (*env)->FindClass(env, "com/study/jni/HelloWorld");
    (env)->RegisterNatives(env, clazz, gMethods, NELEM(gMethods));
    return JNI_VERSION_1_6;
}
*/

